import crypto from 'node:crypto';
import path from "node:path";
import fs from 'node:fs';
import ffmpeg from 'fluent-ffmpeg';
import ffmpegPath from 'ffmpeg-static';
import ffprobePath from 'ffprobe-static';
import { getTempPath } from '../../utils';

export class IndexController {
  index(c){
    return c.json({ message: 'Hello!' })
  }

  async ffmpeg(c){
    console.log(ffmpegPath, ffprobePath)

    const videoUrl = 'https://cos.kuaijingai.com/upload/shotstack/video/2213/92650/667430185445285889_153_1.mp4'

    // 生成唯一路径
    const uniquePath = crypto.randomBytes(16).toString('hex');
    const outputDir = path.join(getTempPath(), 'shotstack/video');
    const converFileName = `${uniquePath}_cover.png`
    const coverPath = path.join(outputDir, converFileName);

    // 确保输出目录存在
    if (!fs.existsSync(outputDir)) {
      fs.mkdirSync(outputDir, { recursive: true });
    }

    // 使用 ffmpeg 生成封面
    await new Promise((resolve, reject) => {
      ffmpeg(videoUrl)
        .setFfmpegPath(ffmpegPath.replace('app.asar', 'app.asar.unpacked'))
        .setFfprobePath(ffprobePath.path.replace('app.asar', 'app.asar.unpacked'))
        .on('error', reject)
        .screenshots({
          count: 1,
          filename: converFileName,
          folder: outputDir
        })
        .on('end', resolve);
    });

    return c.json({ message: coverPath })
  }
}